'''    
Created on 27. 1. 2014

@author: DZCPB72
'''

import cherrypy


import logging
import liven.data as data
import time
import schedule

from apscheduler.scheduler import Scheduler

log = logging.getLogger(__name__)

class DetectorService:
    
    def __init__(self):
        log.debug("DetectorService:initializing...")
        pass
    
    
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def index(self):
        log.debug("DetectorService.index")
        out = []
        for i in data.Data().detectors():
            out.append(self.serialize(i))
        return out
        
        
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def hwid(self, h):
        log.debug("DetectorService.hwid: hwid=%s" % (h))
        d = data.Data()
        l = d.detectors(hwid=h)
        if len(l) > 0:
            return self.serialize(l[0])
        else:  
            raise cherrypy.NotFound()
    
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def place(self, h):
        log.debug("DetectorService.place: place=%s" % (h))
        return [ self.serialize(i) for i in data.Data().detectors(place=h) ]
    
    def serialize(self, detector):
        return {
                'hwid': detector.hwid,
                'place':  detector.place,
                'dtype': detector.dtype
                }
    
    
class MeasureService:
    
    def __init__(self):
        pass
        
    @cherrypy.expose
    @cherrypy.tools.json_out()  
    def hwid(self, h):
        log.debug("MeasureService.hwid: hwid=%s" % h)
        l = data.Data().detectors(hwid=h)
        if (len(l) > 0):
            return self._ser(l[0].measure())
        else:
            raise cherrypy.NotFound()
        
    def _ser(self, m):
        return {
                'hwid': m.hwid,
                'place': m.place,
                'dtype': m.dtype,
                'unit': m.unit,
                'ctime': int(time.mktime(m.ctime.timetuple())),
                'value': m.value
                }
    
        
   
if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
  

    
    cherrypy.tree.mount(
        DetectorService(), '/detector',
        {'':
            {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}
        }               
    )
    cherrypy.tree.mount(
        MeasureService(), '/measure',
         {'':
            {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}
        }   
    )
    
    
    sched = Scheduler()
    sched.add_interval_job(schedule.DetectorJob().run, seconds=10)
    sched.start()
    
    cherrypy.engine.start()
    cherrypy.engine.block()
    